package com.bole.shiro;

import com.alibaba.fastjson.JSONObject;
import com.bole.data.Result;
import com.bole.dto.permission.AdminDto;
import com.bole.feign.AdminFeign;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class UserRealm extends AuthorizingRealm {

//    @Autowired
//    private UserService userService;

    @Autowired
    private AdminFeign adminFeign;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("授权逻辑");
        // 授权
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        List<String> permissionList = new ArrayList<>();
        authorizationInfo.addStringPermissions(permissionList);
        return authorizationInfo;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        System.out.println("进入认证方法...");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 获取用户名
        String username = token.getUsername();
        // 判断用户名
//        TbUser user = userService.getUserByName(username);
        Result result = adminFeign.getByName(username);
//        AdminDto admin = (AdminDto) result.getData();
        AdminDto admin = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), AdminDto.class);
        if (admin == null) {
            // 用户不存在
            return null;
        }
        // 判断密码
        return new SimpleAuthenticationInfo(
                admin, admin.getPassword(), ByteSource.Util.bytes(admin.getSalt()), "");
//        return null;
    }
}
